#include "config_parse.h"
#include <cJSON.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int config_open_json(config_t* conf, const char* file) {

}

static int config_parse_json_node(cJSON *jmsg, conf_node_t **node);

static int config_parse_json_array(cJSON *jmsg, conf_node_t *node) {
    int array_num = cJSON_GetArraySize(jmsg);
    int i = 0;
    conf_node_t *last;
    for(int i=0; i<array_num; i++) {
        cJSON *js = cJSON_GetArrayItem(jmsg, i);
        if(!i) {
            i = 1;
            config_parse_json_node(js, &node->first_child);
            last = node->first_child;
        } else {
            config_parse_json_node(js, &last->next);
            last = last->next;
        }
    }
}

static int config_parse_json_object(cJSON *jmsg, conf_node_t *node) {
    cJSON *attr;
    int i = 0;
    conf_node_t *last;
    for (attr = jmsg->child; attr; attr = attr->next){
        if(!i) {
            i = 1;
            config_parse_json_node(attr, &node->first_child);
            last = node->first_child;
        } else {
            config_parse_json_node(attr, &last->next);
            last = last->next;
        }
    }
}

static int config_parse_json_node(cJSON *jmsg, conf_node_t **node) {
    *node = (conf_node_t *)calloc(1, sizeof(conf_node_t));
    (*node)->name = (char *)calloc(strlen(jmsg->string)+1, 1);
    strcpy((*node)->name, jmsg->string);
    if(cJSON_IsArray(jmsg)) {
        config_parse_json_array(jmsg, *node);
    } else if(cJSON_IsObject(jmsg)){
        config_parse_json_object(jmsg, *node);
    } else if(cJSON_IsBool(jmsg)){
        (*node)->value = (char *)calloc(6, 1);
        if(cJSON_IsTrue(jmsg)) {
            strcpy((*node)->value, "true");
        } else {
            strcpy((*node)->value, "false");
        }
    } else if(cJSON_IsNumber(jmsg)){
        (*node)->value = (char *)calloc(50, 1);
        sprintf((*node)->value, "%lf", jmsg->valuedouble);
    } else if(cJSON_IsString(jmsg) || cJSON_IsRaw(jmsg)){
        (*node)->value = (char *)calloc(strlen(jmsg->valuestring)+1, 1);
        strcpy((*node)->value, jmsg->valuestring);
    }
}

int config_parse_json(config_t* conf, const char* data, int size) {
    cJSON* jroot = cJSON_Parse(data);
    if(jroot == NULL) {
        return -2;
    }

    config_parse_json_node(jroot, &conf->first_node);
    cJSON_Delete(jroot);
}